import java.util.Queue;

/**
 * @ClassName Code07_BSAwesome
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/12/1 20:29
 */
public class Code07_BSAwesome {

    // 在array上，寻找局部最小值
    public static int getLessIndex(int[] array) {
        if (array == null || array.length == 0) {
            return -1;
        }
        if (array.length == 1 || array[0] < array[1]) {
            return 0;
        }
        if (array[array.length - 1] < array[array.length - 2]) {
            return array.length - 1;
        }
        int L = 1;
        int R = array.length - 2;
        while (L < R) {
            int mid = L + ((R - L) >> 1);
            if (array[mid] > array[mid - 1]) {
                R = mid - 1;
            } else if (array[mid] > array[mid + 1]) {
                L = mid + 1;
            } else {
                return mid;
            }
        }
        // 剩下 L 和 R 是相同的
        return L;
    }

    // 验证得到的结果是不是局部最小
    public static boolean isRight(int[] array, int index) {
        if (array.length <= 1) {
            return true;
        }
        if (index == 0) {
            return array[0] < array[1];
        }
        if (index == array.length - 1) {
            return array[array.length - 1] < array[array.length - 2];
        }
        return array[index - 1] > array[index] && array[index] < array[index + 1];
    }

    // 生成相邻不相等的数组
    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] array = new int[(int) (Math.random() * maxSize) + 1];
        array[0] = (int) (Math.random() * maxValue) - (int) (Math.random() * maxValue);
        for (int i = 1; i < array.length; i++) {
            do {
                array[i] = (int) (Math.random() * maxValue) - (int) (Math.random() * maxValue);
            } while (array[i] == array[i - 1]);
        }
        return array;
    }

    public static void main(String[] args) {
        int testTimes = 500000;
        int maxSize = 30;
        int maxValue = 100;
        System.out.println("测试开始");
        for (int i = 0; i < testTimes; i++) {
            int[] randArray = generateRandomArray(maxSize,maxValue);
            int ans = getLessIndex(randArray);
            if (!isRight(randArray,ans)) {
                System.out.println("测试异常！！！");
                break;
            }
        }
        System.out.println("测试结束");
    }

}
